<script setup lang="ts" name="SelectWorkActivity">

import { GetOperationProcessList } from "@/api/tally";
import { onMounted, ref, watch } from "vue";
import type { ProcessData } from "@/utils/interface";

const input = defineProps(["ids", "shipLand"]);
const emit = defineEmits(["isOpen", "selectedProcess"]);

const loading = ref(true);
const processList = ref([] as ProcessData[]);

onMounted(() => {
  init();
});

watch(
  () => input.shipLand,
  () => {
    init();
  },
  { immediate: true }
);

function init() {
  loading.value = true;
  GetOperationProcessList({ shipLand: input.shipLand, isActivity: "Y" }).then(
    (res: any) => {
      processList.value = res.data as ProcessData[];
      if (input.ids.length > 0) {
        processList.value.forEach(item => {
          item.isSelected = false;
          input.ids.forEach((id: string) => {
            if (item.id === id) {
              changeSelection(item);
            }
          });
        });
      }
      loading.value = false;
    }
  );
}

function changeSelection(item: ProcessData) {
  item.isSelected = !item.isSelected;
}

function selectedProcessFormat(): any {
  const res = {
    processIds: [] as string[],
    processNames: "" as string
  };

  let idList: string[] = [];
  let nameList: string[] = [];
  processList.value.forEach(item => {
    if (item.isSelected) {
      idList.push(item.id);
      nameList.push(item.name);
    }
  });
  res.processIds = idList;
  res.processNames = nameList.join(",");
  return res;
}

function returnRes() {
  emit("selectedProcess", selectedProcessFormat());
  showPop(false);
}

function showPop(show: boolean) {
  emit("isOpen", show);
}
</script>

<template>
  <div class="flex-col h-[auto] p-[20px] w-full" style="background: #f6f6f6">
    <div class="flex h-[30px] justify-between">
      <div
        class="flex justify-center items-center h-full text-center text-base"
      >
        选择作业活动
      </div>
      <div
        class="flex h-full justify-center items-center text-center text-base"
      >
        <div class="text-sky-500" @click="returnRes">确定</div>
      </div>
    </div>
    <div class="flex py-[12px] w-full h-auto flex-wrap gap-2">
      <van-loading
        class="flex w-full justify-center h-[80px] items-center"
        v-if="loading"
        color="#1989fa"
      />
      <div
        :class="{ selected: item.isSelected, unselected: !item.isSelected }"
        class="flex border-2 border-white py-[5px] px-[10px] w-auto text-sm rounded"
        v-for="item in processList"
        :key="item.id"
        @click="changeSelection(item)"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.unselected {
  background: #ffffff;
  color: #000000;
}
.selected {
  background: #3869fc;
  color: #ffffff;
}
</style>
